package com.example.administrator.commonlibrary.bese;



import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.example.administrator.commonlibrary.R;
import com.example.administrator.commonlibrary.utils.NoSlideColseActivityAddUtils;
import com.example.administrator.commonlibrary.utils.ToastUtils;
import com.example.administrator.commonlibrary.utils.UnitConversion;
import com.example.administrator.commonlibrary.utils.rxjava.RxBus;
import com.example.administrator.commonlibrary.wholehelper.LoadingDialogHelper;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;


/**
 * @author wang_hong_wei
 * @description MVP Activity 解绑的基类
 * @Date 2018-5-30
 */
public abstract class BaseViewActivity<T extends BaseContract.BasePresenter> extends BaseActivity   {
    protected T mPresenter;
    private CompositeDisposable mCompositeDisposable;
    private AlertDialog mDialogDefault;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mCompositeDisposable = new CompositeDisposable();
        daggerInject(null);
        // 初始化Presenter
        mPresenter = initPresenter();
        mPresenter.attachView(this);
        myOnCreate();
        setSubscription(addSubscription());//用Rxjava2 发送消息 在子类中重写此方法就可以调用---addSubscription()
    }
    protected <E>void daggerInject(E module){};//用于实例化presenter层对象在attachView 之前运行，防止报null
    protected abstract T initPresenter();
    protected abstract void myOnCreate();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        if (mCompositeDisposable != null) {
            mCompositeDisposable.dispose();
        }
    }

    public Consumer addSubscription(){
        return null;
    }
    private void setSubscription(Consumer consumer) {
        if (consumer == null) return;
        if (mCompositeDisposable == null) {
            throw new NullPointerException("mCompositeDisposable 不能为null-----");
        }
        mCompositeDisposable.add(RxBus.getInstance().toObservable(Object.class).subscribe(consumer));
    }

    /*
     *全局上下文
     * */
    @Override
    public Context getContext() {
        return getApplicationContext();
    }


    @Override
    public void showLoadingDialog() {
      if (mDialogDefault == null) mDialogDefault = LoadingDialogHelper.getInstance().createDialog(this);
        if (isFinishing() || mDialogDefault.isShowing()) {
            return;
        }
        mDialogDefault.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                // TODO: 2017/6/5  onCancel...
                if (mPresenter!=null)
                    mPresenter.cancelRequest();
            }
        });
        //设置宽高必须在show 之后才有作用
        mDialogDefault.show();
        mDialogDefault.getWindow().setLayout(UnitConversion.dp2px(this,100),UnitConversion.dp2px(this,100));
        View view= View.inflate(this, R.layout.dialog_load,null);
        mDialogDefault.getWindow().setContentView(view);//为了去掉标题，只能使用这种方法 配合style 中的样式
    }

    @Override
    public void dismissLoadingDialog() {
      if (mDialogDefault == null || !mDialogDefault.isShowing() || !isActive) {
            return;
        }
        mDialogDefault.cancel();
    }

    @Override
    public void showToast(String content) {
        ToastUtils.showToast(this,content);
    }

    /*
     * 设置横竖屏
     * */

    @Override
    protected int getScreenOrientation() {
        return ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT;
    }


    /**
     * 点击非焦点区域隐藏软软盘
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);

    }

    private boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            // 获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
}
